package com.atguigu.juc.t5;

import java.util.Random;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;


public class Apple {
    public Integer num = 10;

    Lock lock = new ReentrantLock();//true，false，公平非公平


    public void getApple() {
        boolean b1 = false;
        try {
            // lock.lock();// 默认没有拿到所会等待
            // b = lock.tryLock();// 没有拿到锁不等待，而是直接返回false
            try {
                b1 = lock.tryLock(2, TimeUnit.SECONDS);// 等待2秒，拿到锁返回true，等待2秒没拿到锁返回false
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            if (b1) {
                if (num > 0) {
                    System.out.println(Thread.currentThread().getName() + "来摘苹果。。。");
                    try {
                        TimeUnit.SECONDS.sleep(new Random().nextInt(3) + 1);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                    num--;
                    System.out.println(Thread.currentThread().getName() + "摘了苹果，还剩" + num + "个");
                } else {
                    System.out.println(Thread.currentThread().getName() + "没有摘到苹果，没有苹果了");
                }
            } else {
                System.out.println(Thread.currentThread().getName() + "没有拿到锁，太忙，回家了，不摘了");
            }
        } finally {
            if (b1) {
                lock.unlock();
            }
        }
    }
}
